package com.bigpay.app.polling.listener;

import java.util.Date;
import java.util.Map;

import javax.jms.Message;
import javax.jms.MessageListener;

import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigpay.app.polling.core.PollingPersist;
import com.bigpay.app.polling.core.PollingQueue;
import com.bigpay.app.polling.entity.PollingParam;
import com.bigpay.common.core.exception.BizException;
import com.bigpay.notify.entity.RpNotifyRecord;
import com.bigpay.notify.enums.NotifyStatusEnum;
import com.bigpay.notify.enums.NotifyTypeEnum;

/**
 * 轮询消息监听
 */
public class PollingMessageListener implements MessageListener {
	private static final Log log = LogFactory.getLog(PollingMessageListener.class);

	@Autowired
	private PollingQueue pollingQueue;

	@Autowired
	private PollingPersist pollingPersist;

	@Autowired
	private PollingParam pollingParam;

	@SuppressWarnings("static-access")
	public void onMessage(Message message) {
		try {
			ActiveMQTextMessage msg = (ActiveMQTextMessage) message;
			final String msgText = msg.getText();
			log.info("== receive message:" + msgText);

			JSON json = (JSON) JSONObject.parse(msgText);
			RpNotifyRecord notifyRecord = JSONObject.toJavaObject(json, RpNotifyRecord.class);
			if (notifyRecord == null) {
				return;
			}
			// log.info("pollingParam:" + pollingParam);
			notifyRecord.setStatus(NotifyStatusEnum.CREATED.name());
			notifyRecord.setCreateTime(new Date());
			notifyRecord.setEditTime(new Date());
			notifyRecord.setLastNotifyTime(new Date());
			notifyRecord.setNotifyTimes(0); // 初始化通知0次
			if(notifyRecord.getNotifyType().equals(NotifyTypeEnum.PROXY_PAY.name())){
				//代付发起一次
				notifyRecord.setLimitNotifyTimes(1); 
			}else{
				notifyRecord.setLimitNotifyTimes(pollingParam.getMaxNotifyTimes()); // 最大通知次数
			}
			Map<Integer, Integer> notifyParams = pollingParam.getNotifyParams();
			notifyRecord.setNotifyRule(JSONObject.toJSONString(notifyParams)); // 保存JSON

			try {

				pollingPersist.saveNotifyRecord(notifyRecord); // 将获取到的通知先保存到数据库中
				pollingQueue.addToNotifyTaskDelayQueue(notifyRecord); // 添加到通知队列(第一次通知)

			}  catch (BizException e) {
				log.error("BizException :", e);
			} catch (Exception e) {
				log.error(e);
			}
		} catch (Exception e) {
			log.error(e);
		}
	}

}
